package com.example.springbootdemo;


import com.google.gson.Gson;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//地址参数，接收用户id
@ServerEndpoint("/websocket/{id}")
@Component
public class WebSocketAction {

    //会话容器,必须是静态
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    //id 用户标识
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) {
        sessionMap.put(id, session);
        //将当前用户id,写入会话
        session.getUserProperties().put("id", id);
        Msg msg = new Msg();
        sessionMap.forEach((i, s) -> {
            msg.getOnlines().add(i);
        });
        msg.setAuthor(id);
        msg.setText(id + "上线了");

        String json = new Gson().toJson(msg);
        sessionMap.forEach((i, s) -> {
            try {
                s.getBasicRemote().sendText(json);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }


    //断开连接
    @OnClose
    public void onClose(Session session) {
        String id = (String) session.getUserProperties().get("id");
        sessionMap.remove(id);
        Msg msg = new Msg();
        sessionMap.forEach((i, s) -> {
            msg.getOnlines().add(i);
        });
        msg.setAuthor(id);
        msg.setText(id + "下线了");
        String json = new Gson().toJson(msg);
        sessionMap.forEach((i, s) -> {
            try {
                s.getBasicRemote().sendText(json);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @OnMessage
    public void onMessage(String msg, Session session) {
        String id = (String) session.getUserProperties().get("id");
        Msg m = new Msg();
        m.setAuthor(id);
        m.setText(msg);
        String json = new Gson().toJson(msg);
        sessionMap.forEach((i, s) -> {
            try {
                s.getBasicRemote().sendText(json);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}


@Data
class Msg {
    //发送者
    String author;
    //在线人
    List<String> onlines = new ArrayList<>();
    //信息
    String text;
}
